package com.huizluo.module4.copydir;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CopyDir {
    private String srcDir;
    private String dstDir;
    private ExecutorService pool;

    public CopyDir(String srcDir, String dstDir) {
        this.srcDir = srcDir;
        this.dstDir = dstDir;
        this.pool = Executors.newFixedThreadPool(5);
    }

    void Copy() throws IOException {

        File src = new File(this.srcDir);
        if (!src.exists()){
            throw new FileNotFoundException();
        }
        File dst = new File(this.dstDir);
        if (!dst.exists()){
            if (src.isFile()){
                dst.createNewFile();

            }else{
                dst.mkdir();
            }
        }

        this.Run(src,dst);

        this.pool.shutdown();
    }


    private void Run(File src,File dst) throws IOException {
        //如果是一个文件，直接拷贝
        if (src.isFile()){
            CopyFile cf = new CopyFile(src,dst);
            this.pool.submit(cf);
            return;
        }

        if (src.isDirectory()){
            //src 是一个目录
            File[] files = src.listFiles();
            for (File f : files){
                File d = new File(dst.getPath() + File.separator + f.getName());
                if (f.isFile()){
                    d.createNewFile();
                    CopyFile cf = new CopyFile(d,f);
                    this.pool.submit(cf);
                }

                if (f.isDirectory()){
                    d.mkdir();
                    Run(f,d);
                }

            }
        }

    }
}
